﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using TheLogWatcher.Properties;

namespace TheLogWatcher
{
    public partial class LogFormatConfig : Form
    {
        public LogFormatConfig()
        {
            InitializeComponent();
            loadAndBuildLogFormat(0);
        }

        private int currentFormatIndex;

        /// <summary>
        ///     Loads the specified log format to the current
        ///     active log format and builds up the ToolStripPanel
        ///     with all entries.
        /// </summary>
        /// <param name="index"></param>
        private void loadAndBuildLogFormat(int index)
        {
            FormatSettings loadedFormat = null;
            //Formats formats = StaticXmlStorage.getCustomLogFormats();
            List<FormatSettings> formats = PredefinedFormats.Formats;
            if (index != -1)
            {
                loadedFormat = formats[index];
            }
            else
            {
                // No element is requested, build up new panel entries with default values.
            }
            this.currentFormatIndex = loadedFormat.Index;
            this.toolStripContainer.TopToolStripPanel.Controls.Clear();
            this.listBoxLogFormats.Items.Clear();

            //FormatConfigs formatConfigs = StaticXmlStorage.getLogFormatBaseDefs();
            FormatConfigs formatConfigs = PredefinedConfigs.Configs[0];
            if (loadedFormat == null)
            {
                foreach (FormatConfigsType type in formatConfigs.FormatTypes)
                {
                    if (type.Name != null)
                    {
                        ToolStrip formatType = new ToolStrip();
                        formatType.AutoSize = false;
                        formatType.GripMargin = new Padding(6);
                        formatType.LayoutStyle = ToolStripLayoutStyle.VerticalStackWithOverflow;
                        formatType.Location = new Point(type.X, type.Y);
                        formatType.Padding = new Padding(10);
                        formatType.Size = new Size(90, 70);

                        ToolStripTextBox textBox = new ToolStripTextBox();
                        textBox.Text = type.Text;
                        formatType.Items.Add(textBox);
                        if (type.Name != null && !type.Name.Equals("Text"))
                        {
                            ToolStripDropDownButton ddButton = new ToolStripDropDownButton(type.Name);
                            foreach (FormatConfigsTypeProperty property in type.Properties)
                            {
                                string description = property.DateFormat + " (e.g. " + property.Description + ")";
                                ToolStripMenuItem dropDownItem = new ToolStripMenuItem(description);
                                dropDownItem.Click += new EventHandler(toolStrip_ItemClicked);
                                if (type.DefaultProperty != 0 && type.DefaultProperty == property.ID)
                                {
                                    dropDownItem.Checked = true;
                                }
                                ddButton.DropDownItems.Add(dropDownItem);
                            }
                            formatType.Items.Add(ddButton);
                        }
                        toolStripContainer.TopToolStripPanel.Controls.Add(formatType);
                    }
                }

                // Create a FormatSettings object
                FormatSettings sets = new FormatSettings();
                sets.Name = formatConfigs.Name;
                sets.Index = index;
                sets.FormatTypes = new ArrayList();
                foreach (FormatConfigsType confType in formatConfigs.FormatTypes)
                {
                    FormatSettingsType thisType = new FormatSettingsType(confType.Name, confType.X, confType.Y, confType.Text);
                    thisType.PropertyID = confType.DefaultProperty;
                    sets.FormatTypes.Add(thisType);
                }
                this.currentFormatIndex = index;
                int entryPos = this.listBoxLogFormats.Items.Add(sets.getListName());
                this.listBoxLogFormats.SelectedIndex = entryPos;
                loadedFormat = sets;
            }
            else
            {
                int entryPos = this.listBoxLogFormats.Items.Add(loadedFormat.getListName());
                this.listBoxLogFormats.SelectedIndex = entryPos;

                foreach (FormatSettingsType type in loadedFormat.FormatTypes)
                {
                    if (type.Name != null)
                    {
                        ToolStrip formatType = new ToolStrip();
                        formatType.AutoSize = false;
                        formatType.GripMargin = new Padding(6);
                        formatType.LayoutStyle = ToolStripLayoutStyle.VerticalStackWithOverflow;
                        formatType.Location = new Point(type.X, type.Y);
                        formatType.Padding = new Padding(10);
                        formatType.Size = new Size(90, 70);

                        ToolStripTextBox textBox = new ToolStripTextBox();
                        textBox.Text = type.Text;
                        formatType.Items.Add(textBox);
                        if (type.Name != null && !type.Name.Equals("Text"))
                        {
                            ToolStripDropDownButton ddButton = new ToolStripDropDownButton(type.Name);
                            foreach (FormatConfigsType configType in formatConfigs.FormatTypes)
                            {
                                if (configType.Name.Equals(type.Name))
                                {
                                    foreach (FormatConfigsTypeProperty property in configType.Properties)
                                    {
                                        string description = property.DateFormat + " (e.g. " + property.Description + ")";
                                        ToolStripMenuItem dropDownItem = new ToolStripMenuItem(description);
                                        dropDownItem.Click += new EventHandler(toolStrip_ItemClicked);
                                        if (type.PropertyID != 0 && type.PropertyID == property.ID)
                                        {
                                            dropDownItem.Checked = true;
                                        }
                                        ddButton.DropDownItems.Add(dropDownItem);
                                    }
                                    break;
                                }
                            }
                            formatType.Items.Add(ddButton);
                        }
                        toolStripContainer.TopToolStripPanel.Controls.Add(formatType);
                    }
                }
            }
            this.textBoxRegEx.Text = loadedFormat.compileRegEx();
            this.textBoxFormatName.Text = loadedFormat.Name;
            this.textBoxExample.Text = loadedFormat.generateExample();
        }

        /// <summary>
        ///     Saves the currently active log format with all properties.
        /// </summary>
        private void saveLogFormat()
        {
            FormatSettings currentSetting = null;
            //Formats formats = StaticXmlStorage.getCustomLogFormats();
            List<FormatSettings> formats = PredefinedFormats.Formats;

            if (formats != null && this.currentFormatIndex != -1 && formats.Count > this.currentFormatIndex)
            {
                currentSetting = formats[this.currentFormatIndex];
            }
            if (currentSetting == null)
            {
                currentSetting = new FormatSettings();
            }
            currentSetting.Name = this.textBoxFormatName.Text;

            // Save properties of each format object of the current log format
            Control.ControlCollection col = toolStripContainer.TopToolStripPanel.Controls;
            ArrayList formatTypes = new ArrayList();
            //FormatConfigs formatConfigs = StaticXmlStorage.getLogFormatBaseDefs();
            FormatConfigs formatConfigs = PredefinedConfigs.Configs[0];
            foreach (ToolStrip item in col)
            {
                string typeName = item.Text;
                FormatSettingsType type = new FormatSettingsType(typeName, item.Location.X, item.Location.Y, item.Items[0].Text);
                if (item.Items.Count == 2)
                {
                    ToolStripDropDownButton button = (ToolStripDropDownButton)item.Items[1];
                    for (int i = 0; i < button.DropDownItems.Count; i++)
                    {
                        ToolStripMenuItem but = button.DropDownItems[i] as ToolStripMenuItem;
                        if (but.Checked)
                        {
                            foreach (FormatConfigsType configType in formatConfigs.FormatTypes)
                            {
                                if (configType.Name.Equals(type.Name))
                                {
                                    FormatConfigsTypeProperty prop = configType.Properties[i] as FormatConfigsTypeProperty;
                                    type.PropertyID = prop.ID;
                                    break;
                                }
                            }
                            break;
                        }
                    }
                }
                formatTypes.Add(type);
            }
            currentSetting.FormatTypes = formatTypes;
            formats[this.currentFormatIndex] = currentSetting;

            string formatSettingsFile = Settings.Default.FormatSettingsFile;
            string startDirectory = Settings.Default.StartDirectory;
            //ObjectXMLSerializer<Formats>.Save(formats, startDirectory + formatSettingsFile);
        }

        public class SortByLocation : IComparer
        {
            #region IComparer Members

            int IComparer.Compare(object obj1, object obj2)
            {
                Control left = (Control)obj1;
                Control right = (Control)obj2;
                int x1 = left.Location.X;
                int y1 = left.Location.Y;
                int x2 = right.Location.X;
                int y2 = right.Location.Y;
                if ((x1 < x2 && y1 <= y2) || y1 < y2)
                {
                    return -1;
                }
                else if ((x1 > x2 && y1 == y2) || y1 > y2)
                {
                    return 1;
                }
                return 0;
            }

            #endregion
        }

        private void btnNewEntry_Click(object sender, EventArgs e)
        {
            //this.currentFormatSettings = new LogFormatOld();
            //saveLogFormat();
            //updateGUI();
            //this.textBoxRegEx.Text = this.currentFormatSettings.RegEx;
            
            //// Select the newly created format
            //this.listBoxLogFormats.SelectedIndex = this.currentFormatSettings.Index;
        }

        private void toolStrip_ItemClicked(object sender, EventArgs e)
        {
            if (sender.GetType() == typeof(ToolStripMenuItem))
            {
                ToolStripMenuItem item = (ToolStripMenuItem)sender;

                int index = -1;
                if (!item.Checked)
                {
                    ToolStrip toolstrip = item.GetCurrentParent();

                    for (int i = 0; i < toolstrip.Items.Count; i++)
                    {
                        ToolStripMenuItem menuItem = toolstrip.Items[i] as ToolStripMenuItem;
                        if (menuItem == item)
                        {
                            menuItem.Checked = true;
                            index = i;
                        }
                        else
                        {
                            menuItem.Checked = false;
                        }
                    }
                }
                loadAndBuildLogFormat(index);
            }
        }

        private void listBoxLogFormats_SelectedIndexChanged(object sender, EventArgs e)
        {
            //ListBox listBox = (ListBox)sender;
            //saveLogFormat();
            //loadAndBuildLogFormat(listBox.SelectedIndex);
        }

        private void button2_Click(object sender, EventArgs e)
        {
            loadAndBuildLogFormat(0);
        }
    }
}
